package com.example.testhotload;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;

import com.example.testhotload.diff.BSPatchUtils;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.snackbar.Snackbar;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.core.content.FileProvider;

import android.os.Environment;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;

import java.io.File;


public class  MainActivity extends AppCompatActivity {
    private AlertDialog mDialog;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        FloatingActionButton fab = findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "ZZ", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });

        Snackbar.make(fab, "V2", Snackbar.LENGTH_LONG)
                .setAction("Action", null).show();



//        CheckUpdateUtils.checkUpdate("apk", "1.0.0", new CheckCallBack() {
//            @Override
//            public void onSuccess(UpdateAppInfo updateAppInfo) {
//                String isForce = updateAppInfo.data.lastForce ="1";
//                String downUrl = updateAppInfo.data.updateurl="http://192.168.1.150:7993/testHotLoad.apk";
//                String updateInfo = updateAppInfo.data.upgradeinfo="zzz";
//                String appName  = updateAppInfo.data.appname="testHotLoad";
//                if(isForce.equals("1")&&!TextUtils.isEmpty(updateInfo)){
//                    forceUpdate(MainActivity.this,appName,downUrl,updateInfo);
//
//                }else{
//                    normalUpdate(MainActivity.this,appName,downUrl,updateInfo);
//                }
//            }
//
//            @Override
//            public void onError() {
////                noneUpdate(MainActivity.this);
//                String isForce = "1";
//                String downUrl ="http://192.168.1.150:7993/testHotLoad.apk";
//                String updateInfo ="zzz";
//                String appName  = "testHotLoad";
//                if(isForce.equals("1")&&!TextUtils.isEmpty(updateInfo)){
//                    forceUpdate(MainActivity.this,appName,downUrl,updateInfo);
//
//                }else{
//                    normalUpdate(MainActivity.this,appName,downUrl,updateInfo);
//                }
//            }
//        });
//        try {
//            String SD_FOLDER = Environment.getExternalStorageDirectory()+"/VersionChecker/";
//            String appName = "testHotLoad";
//            String fileName = SD_FOLDER+appName+".apk";
//            File file = new File(fileName);
//            installApk(MainActivity.this,file);
//        }catch (Exception e){
//            e.printStackTrace();;
//            return ;
//        }
    new Thread(new Runnable() {
        @Override
        public void run() {
            patchTest();
        }
    }).start();


    }

    private  void patchTest(){
        String SD_FOLDER = Environment.getExternalStorageDirectory()+"/VersionChecker/";
        File fileV1 = new File(SD_FOLDER+"testHotLoad_V1.apk");
        File filePatch = new File(SD_FOLDER+"v1.2.patch");
        if(fileV1.exists()&&filePatch.exists()){
            //存储权限
            int ret = BSPatchUtils.patch(fileV1.getAbsolutePath(),SD_FOLDER+"test.apk",filePatch.getAbsolutePath());
            if(ret==0){
                Log.i("ATX","合并成功");}
            else
                Log.i("ATX","合并失败");
        }


    }

    private  void installApk(Context ctx,File file){
        Uri uri;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            uri = FileProvider.getUriForFile(ctx, "com.example.testhotload.fileprovider", file);
        } else {
            uri= Uri.fromFile(file);
        }
        Intent install = new Intent(Intent.ACTION_VIEW);
        install.setDataAndType(uri,"application/vnd.android.package-archive");
        install.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        install.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        ctx.startActivity(install);
    }

    private void noneUpdate(final Context context){
//        Toast.makeText(context,"无需更新",Toast.LENGTH_LONG);
        FloatingActionButton fab = findViewById(R.id.fab);
        Snackbar.make(fab, "无需更新", Snackbar.LENGTH_LONG)
                .setAction("Action", null).show();
    }

    private boolean canDownloadState(){
        try{
         int state = this.getPackageManager().getApplicationEnabledSetting("com.android.providers.downloads");
         if(state== PackageManager.COMPONENT_ENABLED_STATE_DISABLED||state==PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED||
         state==PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER){
             return false;
         }
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
        return true;
    }

    private void showDownloadSetting(){
        String packageName = "com.android.providers.downloads";
        Intent intent = new Intent(android.provider.Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        intent.setData(Uri.parse("package:" + packageName));
        startActivity(intent);
    }

    private void forceUpdate(final Context context,final String appName,final String downUrl,String updateInfo){
        mDialog = new AlertDialog.Builder(context).create();
        mDialog.setTitle("强制更新");
        mDialog.setMessage(updateInfo);
        mDialog.setButton(AlertDialog.BUTTON_POSITIVE, "立即更新", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                if(!canDownloadState()){
                    showDownloadSetting();
                    return ;
                }
                AppInnerDownloader.downloadApk(MainActivity.this,downUrl,appName);
//                FileDownloadManager.getInstance(context).StartDownload(downUrl,"下载","APP",appName);
//                DownloadApk.download(context,downUrl,"下载",appName);
            }
        });

        mDialog.setCancelable(false);
        mDialog.show();

    }

    private void normalUpdate(final Context context,final String appName,final String downUrl,String updateInfo){
        mDialog = new AlertDialog.Builder(context).create();
        mDialog.setTitle("普通更新");
        mDialog.setMessage(updateInfo);
        mDialog.setButton(AlertDialog.BUTTON_POSITIVE, "立即更新", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                if(!canDownloadState()){
                    showDownloadSetting();
                    return ;
                }
                AppInnerDownloader.downloadApk(MainActivity.this,downUrl,appName);
            }
        });

        mDialog.setCancelable(false);
        mDialog.show();

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }


}
